'use strict';

const moment = require('moment');

//生成任意长度的正整数验证码
const createCode = (codeLength = 4) => {
    let rdCode = "";
    while (rdCode.length < codeLength) {
        let randomSingleNum = parseInt(Math.random() * 10, 10).toString();
        rdCode = rdCode + randomSingleNum
    };
    return rdCode;
};

const Controller = require('egg').Controller;

class GetSmsController extends Controller {

    async sendSMS() {
        const {
            app,
            ctx
        } = this;
        try {

            // --------------------此处code你的逻辑，比如调用第三方短信接口等等--------------------


        } catch (error) {
            ctx.logger.error(error);
            ctx.monkeyResult(5000);
        }
    }


    async init() {

        const {
            app,
            ctx
        } = this;

        try {

            const {
                mobile
            } = ctx.request.body;

            const {
                codeLength, //验证码位数
                intervalTime //验证码发送间隔限制 => 单位：分钟
            } = app.config.monkeySMS;

            if (!mobile) { //参数为空
                ctx.monkeyResult(1004);
                return;
            };

            if (!ctx.helper.isMobile(mobile)) { //手机号码格式不正确
                ctx.monkeyResult(1102);
                return;
            };

            const mobileResult = await ctx.model.Sms.findByMobile(mobile);

            if (!mobileResult) { //新数据
                const createData = await ctx.model.Sms.create({
                    mobile,
                    verifyCode: createCode(codeLength)
                });
                await this.sendSMS();
                ctx.monkeyResult(0, true);
                return;
            };

            const valueTime = moment(mobileResult.createdAt).add(intervalTime, 'minutes').format('YYYY-MM-DD HH:mm:ss');

            const currentTime = moment().format('YYYY-MM-DD HH:mm:ss');

            const isAfter = moment(currentTime).isAfter(valueTime)

            if (isAfter) { //不在验证码时间限制范围内
                const updateData = await mobileResult.update({
                    mobile,
                    verifyCode: createCode(codeLength),
                    createdAt: currentTime
                });
                await this.sendSMS();
                ctx.monkeyResult(0, true);
                return;
            };

            ctx.monkeyResult(1503, false); //发送频率过高，限制发送

        } catch (error) {
            ctx.logger.error(error);
            ctx.monkeyResult(5000);
        }

    }

}

module.exports = GetSmsController;